package uk.co.agileworks.bidpirate.service;

import java.util.List;

import uk.co.agileworks.bidpirate.model.Bid;

public final class Pager {

	private static final int RESULTS_PER_PAGE = 5;
	private static final int SIZE = 128;

	private final List<Bid> bids;
	private int currentPage;

	public Pager(List<Bid> bids) {
		this.bids = bids;
	}

	public int firstResultOnPage() {
		return (currentPage - 1) * RESULTS_PER_PAGE;
	}

	public int getCurrentPage() {
		return currentPage;
	}

	public String getHtml() {
		StringBuilder html = new StringBuilder(SIZE);
		for (int page = 1; page <= lastPage(); page++) {
			if (currentPage == page) {
				html.append("<u>");
				html.append(page);
				html.append("</u>\n");
			} else {
				html.append("<a href='listBids.html?page=");
				html.append(page);
				html.append("'>");
				html.append(page);
				html.append("</a>\n");
			}
		}
		return html.toString();
	}

	public List<Bid> getPageResults() {
		return bids.subList(firstResultOnPage(), lastResultOnPage() + 1);
	}

	public boolean isShow() {
		return lastPage() > 1;
	}

	public int lastPage() {
		return (bids.size() - 1) / RESULTS_PER_PAGE + 1;
	}

	public int lastResultOnPage() {
		int lastResultOnPage = currentPage * RESULTS_PER_PAGE - 1;
		return lastResultOnPage < bids.size() - 1 ? lastResultOnPage : bids.size() - 1;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage < lastPage() ? currentPage : lastPage();
	}

}
